package com.example.personalinfo.respository;

import android.os.AsyncTask;

import androidx.lifecycle.LiveData;

import com.example.personalinfo.api.Api;
import com.example.personalinfo.db.UserDao;
import com.example.personalinfo.model.User;

import org.jetbrains.annotations.NotNull;

import java.util.concurrent.FutureTask;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class UserRepository {

    private final String TAG = this.getClass().getName();
    private final UserDao userDao;
    private final Api api;

    public UserRepository(UserDao userDao, Api api) {
        this.userDao = userDao;
        this.api = api;
    }

    public LiveData<User> getUser(String name) {
        refresh(name);
        return userDao.getUserByName("liang_hy");
    }

    public void refresh(String name) {
        api.getUser(name).enqueue(new Callback<User>() {
            @Override
            public void onResponse(@NotNull Call<User> call, @NotNull Response<User> response) {
                if (response.body() != null) {
                    System.out.println(response.isSuccessful());
                    insertUser(response.body());
                }
            }

            @Override
            public void onFailure(@NotNull Call<User> call, @NotNull Throwable t) {

            }
        });
    }

    private void insertUser(User user) {
        AsyncTask.execute(() -> userDao.insertUser(user));
    }

}
